class Main {
	
	controller = emo.DigitalOnScreenController("control_base.png", "control_knob.png");
	person = emo.SpriteSheet("person.png", 32, 64, 0, 0);
	grass = emo.MapSprite("grass.png", 288, 218);
	
	coin = emo.Sprite("coin.png");
	score = emo.FontSprite("score", 18);
	coins = 0;
	
    function onLoad() {
    	if (emo.Stage().getWindowWidth() > 320) {
            emo.Stage().setContentScale(emo.Stage().getWindowWidth() / 320.0);
        }
    	
    	local x = emo.Stage().getWindowWidth() / 2;
    	local y = emo.Stage().getWindowHeight() / 2;
    	
    	this.person.moveCenter(x, y);
    	
    	this.controller.move(emo.Stage().getWindowWidth() - this.controller.getWidth(), emo.Stage().getWindowHeight() - this.controller.getHeight());
    	this.controller.updateInterval = 50;
    	
    	local tiles = [
    		[0, 0, 0],
    		[0, 0, 0],
    		[0, 0, 0]
    	];
    	
    	this.grass.setMap(tiles);
    	this.grass.load();
    	
    	this.person.load();
    	this.controller.load();
    	
    	this.coin.load();
    	this.coin.hide();
    	
    	this.coins = 0;
    	this.score.setParam(this.coins);
    	this.score.move(2,2);
    	this.score.color(0,1,0,1);
    	this.score.load();
    	
    	this.grass.setZ(0);
    	this.person.setZ(1);
    	this.coin.setZ(1);
    	this.score.setZ(2);
    	this.controller.setZ(2);
    	
    	randomCoin();
    }
    
    function randomCoin() {
    	local x = emo.Runtime().random(emo.Stage().getWindowWidth());
    	local y = emo.Runtime().random(emo.Stage().getWindowHeight());
    	
    	this.coin.move(x, y);
    	this.coin.show();
    }

    function onDispose() {
        this.person.remove();
        this.controller.remove();
    }
    
    function onControlEvent(controller, controlX, controlY, hasChanged) {
    	local x = this.person.getX() + (controlX / 10);
    	local y = this.person.getY() + (controlY / 10);
    	
    	if (x < 0 || x > emo.Stage().getWindowWidth() - this.person.getWidth()) {
    		x = this.person.getX();	
    	}
    	
    	if (y < 0 || y > emo.Stage().getWindowHeight() - this.person.getHeight()) {
    		y = this.person.getY();	
    	}
    	
    	if (this.person.collidesWith(this.coin)) {
    		this.coins++;
    		this.score.setParam(this.coins);
    		this.score.reload();
    		
    		this.coin.hide();
    		randomCoin();	
    	}
    	
    	if (hasChanged) {
    		local direction = controller.getDirection();
    	
	    	switch(direction) {
				case CONTROL_DOWN:  animate(this.person, 2);  break;	
				case CONTROL_UP:    animate(this.person, 7);  break;	
				case CONTROL_LEFT:  animate(this.person, 13); break;
				case CONTROL_RIGHT: animate(this.person, 19); break;	
				default: this.person.setFrame(0); 
			}
    	} else {
    		this.person.move(x, y);
    	}
    }
    
    function animate(sprite, pos) {
    	sprite.animate(pos, 4, 200, -1);	
    }
    
}

function emo::onLoad() {
    emo.Stage().load(Main());
}
